﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

namespace UnityEngine.UI
{
    public class ActionButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
    {
        public bool isTouchDown = false;
        private int touchId = -1;
        public Image image;

        public void OnPointerDown(PointerEventData eventData)
        {
            if (touchId != -1) return;
            touchId = eventData.pointerId;
            isTouchDown = true;
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            if (touchId != eventData.pointerId) return;
            touchId = -1;
            isTouchDown = false;
        }

        private void OnButtonCancel()
        {
            touchId = -1;
            isTouchDown = false;
        }

        private void OnDisable()
        {
            OnButtonCancel();
        }

        public static bool GetTouchByFingerId(int fingerId, out Touch touch)
        {
            touch = default(Touch);
            if (Input.touchCount == 0 || fingerId < 0)
            {
                return false;
            }
            for (int i = 0; i < Input.touchCount; i++)
            {
                if (Input.GetTouch(i).fingerId == fingerId)
                {
                    touch = Input.GetTouch(i);
                    return true;
                }
            }

            return false;
        }
        private Touch _touch;
        private void Update()
        {
            if (isTouchDown)
            {
                if (touchId != -1)
                {
                    if (GetTouchByFingerId(touchId, out _touch))
                    {
                        switch (_touch.phase)
                        {
                            case TouchPhase.Ended:
                            case TouchPhase.Canceled:
                                OnButtonCancel();
                                return;
                        }
                    }
                    else
                    {
                        OnButtonCancel();
                    }

                }
                image.color = new Color(1, 1, 1, 1f);
            }
            else
            {
                image.color = new Color(1, 1, 1, 0.5f);
            }


        }

    }
}